package com.tx.activemq._01_c_p._04_jms_dependence._041_persistent.topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * 【consumer】 topic 持久化
 */
public class TopicConsumer {

    private static final String ACTIVEMQ_URL = "tcp://192.168.254.30:61616";

    private static final String TOPIC_NAME = "wechat";

    private static final String USER_NAME = "mercury";

    private static final String USER_ID = "0001";

    public static void main(String[] args) throws JMSException, IOException {
        System.out.println("*******1号消费者******");
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        Connection connection = factory.createConnection();
        //位置要移
        connection.setClientID(USER_ID);
        connection.start();

        Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(TOPIC_NAME);

        //设置订阅，参数1：订阅的哪个主题（类似于公众号）。参数2：谁订阅的
        TopicSubscriber topicSubscriber = session.createDurableSubscriber(topic,USER_NAME);

//        MessageConsumer consumer = session.createConsumer(topic);

        topicSubscriber.setMessageListener(msg -> {
            if(msg != null && msg instanceof TextMessage){
                TextMessage textMessage = (TextMessage) msg;
                try {
                    System.out.println(textMessage.getText());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });

        //挂起控制台
        System.in.read();

        topicSubscriber.close();
        session.close();
        connection.close();
    }

}